package com.inspire.springboot.service.imp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.inspire.springboot.constants.CoverageConstants;
import com.inspire.springboot.entity.TestCases;
import com.inspire.springboot.service.CoverageService;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author :inspire
 * @date :Created in 2025/9/30 14:15
 * @description:
 * @modified By:inspire
 * @version:
 */
@Service
public class CoverageServiceImpl implements CoverageService {
    private final OkHttpClient httpClient;
    private final ObjectMapper objectMapper;

    // 构造器注入（推荐方式）
    public CoverageServiceImpl(OkHttpClient httpClient, ObjectMapper objectMapper) {
        this.httpClient = httpClient;
        this.objectMapper = objectMapper;
    }

    @Override
    public String getRelatedCovOfDetail(TestCases testCases){
        String str = reqRelatedCovOfDetail(testCases);
        JSONObject  jsonObject = null;
        if("coverage".equals(testCases.getAccessData())){
            jsonObject = JSONObject.parseObject(str);
        }else if("testProcedure".equals(testCases.getAccessData())){
            jsonObject = new JSONObject();
            jsonObject.put("expect_input","目标板上的测试用例脚本执行成功");
            jsonObject.put("expect_output","上传测试报告到core服务本地，用户可在查看用例功能中看到“查看报告”按钮");
            jsonObject.put("operation_steps","1. 点击用例“执行”按钮\n" +
                    "2. “执行”按钮右侧显示“已完成”");
        }else if ("callChain".equals(testCases.getAccessData())){
            jsonObject = new JSONObject();
            JSONObject jsonObject2 = JSON.parseObject(CoverageConstants.call_chain);
            jsonObject.put("methodCallStack", jsonObject2);
        }else{
            jsonObject = new JSONObject();
        }

        return jsonObject.toJSONString();
    }

    public String reqRelatedCovOfDetail(TestCases testCases) {
        // 序列化对象为 JSON
        String jsonBody;
        try {
            jsonBody = objectMapper.writeValueAsString(testCases);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Failed to serialize TestCases to JSON", e);
        }

        // 创建请求体
        RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json; charset=utf-8"));

        // 构建请求
        Request request = new Request.Builder()
                .url("http://192.168.10.183:3006/zoa/getRelatedCovOfDetail")
                .post(body)
                .addHeader("Accept", "*/*")
                .addHeader("Accept-Encoding", "gzip, deflate, br")
                .addHeader("Connection", "keep-alive")
                .addHeader("Content-Type", "application/json")
                .addHeader("User-Agent", "PostmanRuntime-ApipostRuntime/1.1.0")
                .build();

        // 发送请求
        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("HTTP error: status=" + response.code() + ", body=" + response.body().string());
            }
            ResponseBody responseBody = response.body();
            return responseBody != null ? responseBody.string() : "";
        } catch (IOException e) {
            throw new RuntimeException("Request failed: " + e.getMessage(), e);
        }
    }
}
